import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "../store";
import {
  getToken,
  setToken,
  getLocal,
  setLocal,
  removeToken,
  removeLocal,
} from "@/utils/token";
import { Local } from "@/enums/Local";

interface UserState {
  token: string | undefined | null;
  username: string | undefined | null;

}

const initialState: UserState = {
  token: getToken() || undefined,
  username: getLocal(Local.USER_INFO)?.username || undefined,

};

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    setInfo: (state, action: PayloadAction<UserState>) => {
      state.token = action.payload.token;
      state.username = action.payload.username;

      setToken(action.payload.token);
      setLocal(Local.USER_INFO, { username: action.payload.username });
    },

   

    remove: (state) => {
      state.token = undefined;
      state.username = undefined;
      removeToken();
      removeLocal(Local.USER_INFO);
      removeLocal(Local.USER_NOTIFY_KEY);
    },
  },
});

export const { setInfo, remove } = userSlice.actions;
// 选择器等其他代码可以使用导入的 `RootState` 类型
export const selectUser = (state: RootState) => state.user;

export default userSlice.reducer;
